package cn.nb12.xbox.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RequestUtil {
	
	private static Logger log=LoggerFactory.getLogger(RequestUtil.class);
	
	/**
	 * 发送请求
	 * @param requestUrl 地址
	 * @param params 参数
	 * @param headers 头
	 * @return
	 * @throws IOException
	 */
    public static String sendPost(String requestUrl,String params,Map<String,String> headers,String charSet) throws IOException {

    	try {
			Thread.sleep(50);
		} catch (InterruptedException e1) {
			log.error("延迟发生错误",e1);
		}
    	
        byte[] requestBytes = params.getBytes(charSet); // 将参数转为二进制流
        HttpClient httpClient = new HttpClient();// 客户端实例化
        PostMethod postMethod = new PostMethod(requestUrl);
        // 设置请求头  Content-Type
        postMethod.setRequestHeader("Content-Type", "application/json");
        //postMethod.setRequestHeader("Referer", "https://www.xbox.com/zh-HK/Search?q=just+da");
        if(headers!=null && headers.size()>0) {
        	for (String key : headers.keySet()) {
        		postMethod.setRequestHeader(key, headers.get(key));
			}
        }
        
        InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,
                requestBytes.length);
        RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,
                requestBytes.length, "application/json; charset=utf-8"); // 请求体
        postMethod.setRequestEntity(requestEntity);
        httpClient.executeMethod(postMethod);// 执行请求
        InputStream soapResponseStream = postMethod.getResponseBodyAsStream();// 获取返回的流
        byte[] datas = null;
        try {
            datas = readInputStream(soapResponseStream);// 从输入流中读取数据
        } catch (Exception e) {
        	log.error("从输入流中读取数据错误",e);
        }
        String result = new String(datas, charSet);// 将二进制流转为String
        // 打印返回结果
        // System.out.println(result);

        return result;

    }
    
    /**
	 * 发送请求
	 * @param requestUrl 地址
	 * @param params 参数
	 * @param headers 头
	 * @return
	 * @throws IOException
	 */
    public static String sendGet(String requestUrl,Map<String,String> headers,String charSet) throws IOException {

    	try {
			Thread.sleep(50);
		} catch (InterruptedException e1) {
			log.error("延迟发生错误",e1);
		}
    	
        HttpClient httpClient = new HttpClient();// 客户端实例化
        GetMethod getMethod = new GetMethod(requestUrl);
        if(headers!=null && headers.size()>0) {
        	for (String key : headers.keySet()) {
        		getMethod.setRequestHeader(key, headers.get(key));
			}
        }
        httpClient.executeMethod(getMethod);// 执行请求
        InputStream soapResponseStream = getMethod.getResponseBodyAsStream();// 获取返回的流
        byte[] datas = null;
        try {
            datas = readInputStream(soapResponseStream);// 从输入流中读取数据
        } catch (Exception e) {
        	log.error("从输入流中读取数据错误",e);
        }
        String result = new String(datas, charSet);// 将二进制流转为String

        return result;

    }

    /**
     * 从输入流中读取数据
     * 
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;
    }
}
